package com.aikon.wht.SpEL;

import com.google.common.collect.Lists;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created by haitao.wang on 2016/12/12.
 */
public class TestOfSpEL {

    public static void main(String[] args) throws NoSuchMethodException {
        String helloWorld = "Hello World";
        ExpressionParser parser = new SpelExpressionParser();

        Expression expression = parser.parseExpression("'Hello World'");
        System.out.println(expression.getValue());

        expression = parser.parseExpression("'" + helloWorld + "'" + ".concat('!')");
        System.out.println(expression.getValue(String.class));

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.set(1990, 01, 01);
        Inventor inventor = new Inventor("Tesla", calendar.getTime(), "China");
        expression = parser.parseExpression("country");
        EvaluationContext context = new StandardEvaluationContext(inventor);
        System.out.println(expression.getValue(context));

        System.out.println(expression.getValue(inventor));

        System.out.println(parser.parseExpression("name=='Tesla'").getValue(inventor, Boolean.class));

        context.setVariable("newName", "Tony");
        parser.parseExpression("Name=#newName").getValue(context);
        System.out.println(inventor.getName());

        List<Integer> integerList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
        context = new StandardEvaluationContext(integerList);
        context.setVariable("integerList", integerList);
        System.out.println(parser.parseExpression("#integerList.?[#this>5]").getValue(context));

        StandardEvaluationContext standardEvaluationContext = new StandardEvaluationContext();
        standardEvaluationContext.registerFunction("reverseString",TestOfSpEL.class.getDeclaredMethod("reverseString",new Class[]{String.class}));
        System.out.println(parser.parseExpression("#reverseString('hello')").getValue(standardEvaluationContext));


    }

    public static String reverseString(String input) {
        StringBuilder backwards = new StringBuilder();
        for (int i = 0; i < input.length(); i++)
            backwards.append(input.charAt(input.length() - 1 - i));
        return backwards.toString();
    }



}
